package com.powernode.transaction;

import com.powernode.commons.util.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@SuppressWarnings("all")
/**
 * @Author Arrebol
 * @Date 2024/8/2 18:47
 * @Project jdbc
 * @Description：
 * 实现转账功能（使用事务）
 */
public class JdbcTest2 {
    public static void main(String[] args) {
        double money = 10000;
        Connection conn = null;
        PreparedStatement ps1 = null;
        PreparedStatement ps2 = null;
        try {
            conn = DbUtils.getConnection();
            //开启事务，即将JDBC事务的自动提交机制修改为手动提交
            conn.setAutoCommit(false);
            String sql1 = "update t_act set balance = balance - ? where act_no = ?";
            ps1 = conn.prepareStatement(sql1);
            ps1.setDouble(1, money);
            ps1.setString(2, "act-001");
            int count1 = ps1.executeUpdate();
            System.out.println("execute："+sql1);
            System.out.println("count1 = " + count1);

            //手动模拟异常，测试事务回滚
            System.out.println(1/0);

            String sql2 = "update t_act set balance = balance + ? where act_no = ?";
            ps2 = conn.prepareStatement(sql2);
            ps2.setDouble(1,money);
            ps2.setString(2,"act-002");
            int count2 = ps2.executeUpdate();
            System.out.println("execute："+sql2);
            System.out.println("count2 = " + count2);
            //当整个业务流程成功且完整的结束了，手动提交事务，事务结束
            conn.commit();
            System.out.println("事务提交");
        } catch (Exception e) {
            //只要有任何一个异常发生，就回滚事务
            try {
                System.out.println("回滚事务");
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DbUtils.close(null, ps1, null);
            DbUtils.close(null, ps2, null);
            DbUtils.close(null, null, conn);
        }
    }
}
